package com.mzm.ui.admin;

import java.awt.Frame;
import java.awt.event.ActionEvent;

import javax.swing.AbstractAction;
import javax.swing.JMenu;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPopupMenu;
import javax.swing.SwingUtilities;
import javax.swing.event.TreeSelectionEvent;
import javax.swing.event.TreeSelectionListener;
import javax.swing.tree.TreePath;

import com.mzm.api.ProductInfoDto;
import com.mzm.service.util.CategoryDtoTreeModel;

import dnl.util.ui.PopupUtils;
import dnl.util.ui.WindowUtils;

/**
 * 
 * @author daniel
 */
@SuppressWarnings("serial")
public class CategoriesTreePanel extends javax.swing.JPanel {

	private String currentCatPath;

	protected AdminContext adminContext;

	private NodeSelectionListener nodeSelectionListener;

	private ProductInfoEditingDialog productInfoEditingDialog = new ProductInfoEditingDialog(false,
			(Frame) SwingUtilities.getWindowAncestor(this), true);

	/** Creates new form RmTreePanel */
	public CategoriesTreePanel() {
		initComponents();
		init();
	}

	public void setAdminContext(final AdminContext adminContext) {
		this.adminContext = adminContext;
		refresh();
		PopupUtils.addPopup(categoriesTree, getCategoryTreePopup());
	}

	public void refresh() {
		if (adminContext.getMzmAdminFacade() == null)
			return;
		CategoryDtoTreeModel treeModel = new CategoryDtoTreeModel(adminContext.getMzmAdminFacade()
				.getCategoryTree());
		categoriesTree.setModel(treeModel);
	}

	public void addNodeSelectionListener(final NodeSelectionListener nodeSelectionListener) {
		this.nodeSelectionListener = nodeSelectionListener;
	}

	public void init() {
		categoriesTree.addTreeSelectionListener(new TreeSelectionListener() {

			@Override
			public void valueChanged(final TreeSelectionEvent e) {
				TreePath tpath = e.getPath();
				StringBuilder sb = new StringBuilder();
				Object[] pathElements = tpath.getPath();
				for (Object object : pathElements) {
					if (object.toString().equals("/")) {
						continue;
					}
					sb.append("/");
					sb.append(object.toString());
				}
				currentCatPath = sb.toString();
				if (nodeSelectionListener != null) {
					nodeSelectionListener.nodeSelected(currentCatPath);
				}
				pathTF.setText(currentCatPath);
			}
		});
	}

	private JPopupMenu getCategoryTreePopup() {
		JPopupMenu pop = new JPopupMenu();
		JMenu catMenu = new JMenu("קטגוריה");
		JMenuItem addCategoryMenu = new JMenuItem(new AbstractAction("הוסף") {
			@Override
			public void actionPerformed(ActionEvent e) {
				String s = JOptionPane.showInputDialog(CategoriesTreePanel.this, "הכנס שם קטגוריה");
				if (s != null) {
					adminContext.getMzmAdminFacade().createCategory(
							adminContext.getSelectedPath() + "/" + s);
					refresh();
				}
			}
		});
		JMenuItem deleteCategoryMenu = new JMenuItem(new AbstractAction("מחק") {
			@Override
			public void actionPerformed(ActionEvent e) {
				int userInput = JOptionPane.showConfirmDialog(CategoriesTreePanel.this, "קטגוריה '"
						+ adminContext.getSelectedNode() + "' תמחק");
				if (userInput == JOptionPane.OK_OPTION) {
					adminContext.getMzmAdminFacade().deleteCategory(adminContext.getSelectedPath());
					refresh();
				}
			}
		});
		JMenuItem addProductMenu = new JMenuItem(new AbstractAction("הוסף מוצר") {

			@Override
			public void actionPerformed(ActionEvent e) {
				openNewProductDialog();
			}
		});
		catMenu.add(addCategoryMenu);
		catMenu.add(deleteCategoryMenu);
		pop.add(catMenu);
		pop.add(addProductMenu);
		return pop;
	}

	private void openNewProductDialog() {
		WindowUtils.setWindowSize(productInfoEditingDialog, .5, .5);
		WindowUtils.centerWindow(productInfoEditingDialog);
		productInfoEditingDialog.setVisible(true);
		if (!productInfoEditingDialog.wasCancelled()) {
			ProductInfoDto productInfoDto = productInfoEditingDialog.getProductInfoDto();
			adminContext.getMzmAdminFacade().addProductInfo(currentCatPath, productInfoDto);
			adminContext.refreshProductList();
		}
	}

	/**
	 * This method is called from within the constructor to initialize the form.
	 * WARNING: Do NOT modify this code. The content of this method is always
	 * regenerated by the Form Editor.
	 */
	@SuppressWarnings("unchecked")
	// <editor-fold defaultstate="collapsed"
	// <editor-fold defaultstate="collapsed"
	// desc="Generated Code">//GEN-BEGIN:initComponents
	private void initComponents() {

		jScrollPane1 = new javax.swing.JScrollPane();
		categoriesTree = new javax.swing.JTree();
		pathTF = new javax.swing.JTextField();
		jPanel1 = new javax.swing.JPanel();
		resetTreeJB = new javax.swing.JButton();

		setLayout(new java.awt.BorderLayout());

		javax.swing.tree.DefaultMutableTreeNode treeNode1 = new javax.swing.tree.DefaultMutableTreeNode(
				"-");
		categoriesTree.setModel(new javax.swing.tree.DefaultTreeModel(treeNode1));
		jScrollPane1.setViewportView(categoriesTree);

		add(jScrollPane1, java.awt.BorderLayout.CENTER);

		pathTF.setEditable(false);
		add(pathTF, java.awt.BorderLayout.PAGE_START);

		resetTreeJB.setText("Reset Tree");
		resetTreeJB.addActionListener(new java.awt.event.ActionListener() {
			public void actionPerformed(java.awt.event.ActionEvent evt) {
				resetTreeJBActionPerformed(evt);
			}
		});

		javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
		jPanel1.setLayout(jPanel1Layout);
		jPanel1Layout.setHorizontalGroup(jPanel1Layout.createParallelGroup(
				javax.swing.GroupLayout.Alignment.LEADING).addGroup(
				jPanel1Layout.createSequentialGroup().addContainerGap().addComponent(resetTreeJB)
						.addContainerGap(314, Short.MAX_VALUE)));
		jPanel1Layout.setVerticalGroup(jPanel1Layout.createParallelGroup(
				javax.swing.GroupLayout.Alignment.LEADING).addGroup(
				javax.swing.GroupLayout.Alignment.TRAILING,
				jPanel1Layout.createSequentialGroup()
						.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
						.addComponent(resetTreeJB).addContainerGap()));

		add(jPanel1, java.awt.BorderLayout.PAGE_END);
	}// </editor-fold>//GEN-END:initComponents

	private void resetTreeJBActionPerformed(final java.awt.event.ActionEvent evt) {// GEN-FIRST:event_resetTreeJBActionPerformed
		CategoryDtoTreeModel model = (CategoryDtoTreeModel) categoriesTree.getModel();
		model.reset();
		categoriesTree.setModel(model);
	}// GEN-LAST:event_resetTreeJBActionPerformed

	// Variables declaration - do not modify//GEN-BEGIN:variables
	private javax.swing.JTree categoriesTree;
	private javax.swing.JPanel jPanel1;
	private javax.swing.JScrollPane jScrollPane1;
	private javax.swing.JTextField pathTF;
	private javax.swing.JButton resetTreeJB;
	// End of variables declaration//GEN-END:variables

}
